﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Mimoza.Apps.Console.Resources;
using System.Security.Principal;

namespace Mimoza.Apps.Console
{
    /// <summary>
    /// Create and configure all objects.
    /// </summary>
    public class Configuration
    {
        Settings m_settings;

        Mimoza.DBLayer.Transport.Client.TransportDBLayer m_clientTransportDBLayer;
        Mimoza.ObjectLayer.OL m_objectLayer = null;

        Transport.Connection m_serverConnection;
        Mimoza.PluginLayer.PluginManager m_pluginManager;
        bool m_useLocalDatabase = false;

        public Configuration()
        {
        }

        public void Init(System.Windows.Forms.Form mainForm)
        {
            m_mainForm = mainForm;

            if (!IsUserAceptable()) return;

            FillUseLocalDatabaseFlag();

            m_settings = new Settings();

            if (!UseLocalDatabase)
            {
                m_clientTransportDBLayer = new Mimoza.DBLayer.Transport.Client.TransportDBLayer();
                m_objectLayer = new Mimoza.ObjectLayer.OL(m_clientTransportDBLayer);
            }

            m_pluginManager = new Mimoza.PluginLayer.PluginManager();
            m_pluginManager.Init();

            ConnectToServer();
        }
        public void Deinit()
        {
            CloseConnection();
        }

        public void ConnectToServer()
        {
            if (m_clientTransportDBLayer != null)
            {
                try
                {
                    m_serverConnection = Transport.Transport.CreateConnection("localhost", Settings.ServerTransportPort);
                    m_clientTransportDBLayer.Connect(m_serverConnection);

                    m_serverConnection.CloseHandler += OnConnectionClose;
                }
                catch (Exception e)
                {
                    Mimoza.Common.Logger.Log.Error("Configuration: error in connection to service: " + e.ToString());

                    ShowConnectionErrorAtStartupAndClose();
                }
            }
        }

        public void CheckServerConnection()
        {
            if (m_serverConnection != null) m_serverConnection.Check();
        }

        public Mimoza.ObjectLayer.OL ObjectLayer
        {
            get { return m_objectLayer; }
        }
 
        public Settings Settings
        {
            get { return m_settings; }
        }

        public Mimoza.PluginLayer.PluginManager PluginManager
        {
            get { return m_pluginManager; }
        }

        public bool UseLocalDatabase
        {
            get { return m_useLocalDatabase; }
            set { m_useLocalDatabase = value; }
        }

        private void FillUseLocalDatabaseFlag()
        {
            if (Environment.GetCommandLineArgs().Contains<string>("-db"))
            {
                UseLocalDatabase = true;
            }
            else
            {
                UseLocalDatabase = false;
            }
        }

        private bool IsUserLocalAdmin()
        {
            bool isAdmin = true;
            try
            {
                WindowsIdentity user = WindowsIdentity.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(user);
                isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
            catch (Exception)
            {
                isAdmin = false;
            }
            
            return isAdmin;
        }

        private bool IsUserAceptable()
        {
            if (!IsUserLocalAdmin())
            {
                MessageBox.Show(Resource.Mimoza_Apps_Console_WrongUserError, Resource.Mimoza_Apps_Console_WrongUserCaption,
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                m_mainForm.Close();

                return false;
            }
            else
            {
                return true;
            }
        }

        void CloseConnection()
        {
            //if (m_DBLayer != null)
            //{
            //    m_DBLayer.Disconnect();
            //}
            //if (m_serverConnection != null)
            //{
            //    m_serverConnection.Close();
            //}
        }

        void OnConnectionClose(Transport.Connection conn)
        {
            ShowConnectionErrorAndClose();
        }

        void ShowConnectionErrorAtStartupAndClose()
        {
            MessageBox.Show(Resource.Mimoza_Apps_Console_ConnectError, Resource.Mimoza_Apps_Console_ConnectErrorCaption,
                MessageBoxButtons.OK, MessageBoxIcon.Error);
            m_mainForm.Close();
        }

        void ShowConnectionErrorAndClose()
        {
            MessageBox.Show(Resource.Mimoza_Apps_Console_ConnectionError, Resource.Mimoza_Apps_Console_ConnectErrorCaption,
                MessageBoxButtons.OK, MessageBoxIcon.Error);
            m_mainForm.Close();
        }

        System.Windows.Forms.Form m_mainForm;
    }
}
